<?php
/**
 * Created by PhpStorm.
 * User: hengge
 * Date: 2018/9/26
 * Time: 17:47
 */
namespace app\user\controller;


use app\user\model\UserAddressModel;
use cmf\controller\HomeBaseController;
use think\Db;

class AddressController extends HomebaseController {

    public $user_id = 0;
    public $address_id;

    public function _initialize() {
        parent::_initialize();
        $user_id = cmf_get_current_user_id();
        if($user_id == 0){
            $this->redirect(url('user/login/index'));
        }
        $this->user_id = $user_id;
    }
    // 收货地址
    public function index(){
        //pc显示
        if(!cmf_is_mobile()){
            $addressType = $this->request->get('type/s','');
            $this->address_id = $addressType;
            if($addressType == 'add'){
                $this->addAddress();
            }else{
                $this->editAddress();
            }
            return $this->fetch('address');
        }

        return $this->addresslist();

    }

    /**
     * 获取默认地址
     */
    public function getAddress(){
        $userAdreeModel = new UserAddressModel();
        $def_address = $userAdreeModel->where(array('user_id' => $this->user_id,'is_default'=>1))->find();
        if($def_address){
            $area_id = array();
            $area_id[] = $def_address['province'];
            $area_id[] = $def_address['city'];
            $area_id[] = $def_address['district'];
            $area_id[] = $def_address['twon'];
            $area_id = array_filter($area_id);
            $area_id = implode(',', $area_id);

            $regionList = Db::name('region')->where("id in ($area_id)")->column('id,name');

            $this->assign('regionList', $regionList);
        }
        $this->assign('def_address', $def_address);

        return $this->fetch('default_address');
    }

    /**
     *  显示收货地址列表
     */
    public function addresslist(){
        $userAddresModel = new UserAddressModel();
        $address_list = $userAddresModel->where('user_id = '.$this->user_id)->order("is_default desc")->select()->toArray();

        if($address_list){
            $area_id = array();
            foreach ($address_list as $val){
                $area_id[] = $val['province'];
                $area_id[] = $val['city'];
                $area_id[] = $val['district'];
                $area_id[] = $val['twon'];
            }
            $area_id = array_filter($area_id);
            $area_id = implode(',', $area_id);

            $regionList = Db::name('region')->where("id in ($area_id)")->column('id,name');

            $this->assign('region_list', $regionList);
        }
        $this->assign('address_list', $address_list);


        return $this->fetch('list');
    }

    /*public function ajax_address(){
        $this->display(":ajax_address");
    }*/
   /* //ajax获取地址列表
    public function ajaxAddress(){
        $model = M('UserAddress');
        $address_list = $model->where('user_id = '.$this->user_id)->order("is_default desc")->select();
        if($address_list){
            $area_id = array();
            foreach ($address_list as $val){
                $area_id[] = $val['province'];
                $area_id[] = $val['city'];
                $area_id[] = $val['district'];
                $area_id[] = $val['twon'];
            }
            $area_id = array_filter($area_id);
            $area_id = implode(',', $area_id);
            $regionList = M('address')->where("id in ($area_id)")->getField('id,name');
            $this->assign('regionList', $regionList);
        }


        $this->assign('address_list', $address_list);
        $this->display(":ajax_address");
    }*/


    /**
     * 添加地址 显示和提交
     */
    public function addAddress(){

        if($this->request->isPost()){
            $data = $this->request->post();

            $data['user_id'] = $this->user_id;
            $userModel = new UserAddressModel();
            if(isset($data['is_default'])){
                $data['is_default'] = 1;
                //更新其他默认地址为非默认
                $userModel->where(array('user_id'=>$this->user_id,'is_default'=>1))->update(['is_default'=>0]);
            }
            $count = $userModel->where(array('user_id'=>$this->user_id))->count('id');

            empty($count) ? $data['is_default'] = 1 : true; //没有地址就设为默认


            //省市县三级
            if(!empty($param['s_address'])){
                $s_address = explode(',',$param['s_address']);
                $data['province'] = $s_address[0];
                $data['city'] = $s_address[1];
                $data['district'] = $s_address[2];
            }


            $address = $userModel->isUpdate(false)->allowField(true)->save($data);
            if($address){
                $result = array('status'=>1,'msg'=>'添加成功');
            }else{
                $result = array('status'=>-100,'msg'=>'添加失败');
            }

            return $result;
        }

        //pc需要的是数组  移动端需要的是固定格式的json
        if(cmf_is_mobile()){
            $province = json_encode(get_provs_data());
            $city = json_encode(get_city_data());
            $dists = json_encode(get_dists_data());
        }else{
            $province = get_provs_data(1);
            $city = get_city_data(1);
            $dists = get_dists_data(1);
        }

        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('dists',$dists);

        return $this->fetch('address');
    }

    /**
     * 编辑地址 显示和提交
     */
    public function editAddress(){
        if($this->request->isPost()){
            $userModel = new UserAddressModel();
            $param = $this->request->param();
            if(isset($param['is_default'])){
                $userModel->where(array('user_id'=>$this->user_id,'is_default'=>1))->update(['is_default'=>0]);
            }else{
                $param['is_default'] = 0;
            }
            //默认地址
            $count = $userModel->where(array('user_id'=>$this->user_id))->count('id');

            empty($count) ? $param['is_default'] = 1 : true; //没有地址就设为默认

            //省市县三级
            if(!empty($param['s_address'])){
                $s_address = explode(',',$param['s_address']);
                $param['province'] = $s_address[0];
                $param['city'] = $s_address[1];
                $param['district'] = $s_address[2];
            }

            $address = $userModel->isUpdate(true)->allowField(true)->save($param);

            if($address !== false){
                $result = array('status'=>1,'msg'=>'编辑成功');
            }else{
                $result = array('status'=>-100,'msg'=>'编辑失败');
            }
            return $result;
        }else{
            $address_id = $this->request->param('id/d',0,'intval');
            if($address_id == 0){
                $this->error('参数错误');
            }
            $address = model('UserAddress')->where(array('id'=>$address_id,'user_id'=>$this->user_id))->find()->toArray();
            if(is_null($address)){
                $this->error('参数错误');
            }

            $area_id[] = $address['province'];
            $area_id[] = $address['city'];
            $area_id[] = $address['district'];
            $area_id = array_filter($area_id);
            $area_id = implode(',', $area_id);

            $regionList = Db::name('region')->where("id in ($area_id)")->column('name');
            $regionList = implode(',',$regionList);


            //pc需要的是数组  移动端需要的是固定格式的json
            if(cmf_is_mobile()){
                $province = json_encode(get_provs_data());
                $city = json_encode(get_city_data());
                $dists = json_encode(get_dists_data());
            }else{
                $province = get_provs_data(1);
                $city = get_city_data(1);
                $dists = get_dists_data(1);
            }

            $this->assign('province',$province);
            $this->assign('city',$city);
            $this->assign('dists',$dists);

            $this->assign('address',$address);
            $this->assign('address_list',$regionList);

            return $this->fetch('edit_address');
        }

    }
    /**
     * 设置默认地址
     */
    public function ajaxDefaultAddress(){
        $id = $this->request->param('id/d',0,'intval');
        if($id == 0){
            $this->error('参数错误');
        }else{
            model('UserAddress')->where(array('user_id'=>$this->user_id))->update(array('is_default'=>0));
            model('UserAddress')->where(array('user_id'=>$this->user_id,'id'=>$id))->update(array('is_default'=>1));
        }

    }
    /**
    * 删除收货地址
    */
    public function delAddress(){
        $id = $this->request->param('id/d',0,'intval');
        if($id == 0){
            $this->error('参数错误');
        }

        $address = model('user_address')->where("id = $id")->find();
        $row = model('user_address')->where(array('user_id'=>$this->user_id,'id'=>$id))->delete();
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if($address['is_default'] == 1)
        {
            $address2 = model('user_address')->where("user_id = {$this->user_id}")->field('id')->find();
            $address2 && model('user_address')->where("id = {$address2['id']}")->update(array('is_default'=>1));
        }
        if($row){
            $result = array('status'=>1,'msg'=>'删除成功');
        }else{
            $result = array('status'=>-9,'msg'=>'删除失败');
        }
        return $result;
    }

}